<template>
  <div class="generate-container">
    <!-- 顶部配置区 -->
    <div class="top-section">
      <!-- 文本生成配置 -->
      <section class="config-section">
        <div class="card">
          <h2 class="section-title">📝 文本生成配置</h2>
          <div class="config-content">

            <div class="content-input">
              <div class="model-change">
                <label>输入模式选择：</label>
                <select v-model="form.model" >
                  <option value="textInput">文本输入</option>
                  <option value="topicInput">话题输入</option>
                </select>
              </div>
              <div class="BoxInfo" v-if="form.model==='topicInput'">
                <div class="info-box eventInfo">事件</div>
                <div class="info-box topicInfo">话题</div>
                <div class="info-box topicSelectedInfo">所选话题</div>
              </div>
              <div class="topicBox" v-if="form.model==='topicInput'">
                <div class="eventList">
                  <ul class="event-list">
                    <li v-for="(word, index) in eventTitle" :key="index" @click="selectEvent(index)">
                      {{ index + 1 }}.&nbsp;{{ word }}
                    </li>
                  </ul>
                </div>
                <div class="topicList">
                  <ul class="topic-list">
                    <li v-for="(word, index) in event.hotwords" :key="index" @click="selectTopic(index)">
                      {{ word }}
                    </li>
                    <div v-if="event.hotwords.length == 0" class="empty-topic">请选择一个事件</div>
                  </ul>
                </div>
                <div class="topicSelected">
                  <div class="topicTitle">
                    {{ form.prompt }}
                  </div>
                  <div class="topicContent">
                    话题的相关信息....
                  </div>
                </div>
              </div>
              <textarea
                v-if="form.model==='textInput'"
                v-model="form.prompt"
                placeholder="请输入生成提示词..."
                class="prompt-input"
              ></textarea>
            </div>

            <div class="config-row">
              <div class="config-item">
                <label>正负面比例：</label>
                <div class="slider-group">
                  <input
                    type="range"
                    v-model="form.ratio"
                    min="0"
                    max="10"
                  >
                  <div class="ratio-labels">
                    <span>正面 {{ form.ratio }}</span>
                    <span>负面 {{ 10 - form.ratio }}</span>
                  </div>
                </div>
              </div>

              <div class="config-item">
                <label>生成数量：</label>
                <input
                  type="number"
                  v-model="form.count"
                  min="1"
                  max="10"
                  class="number-input"
                >
              </div>
            </div>

            <button
              class="generate-btn"
              :disabled="isGenerating"
              @click="handleGenerate"
            >
              {{ isGenerating ? '生成中...' : '开始生成' }}
            </button>
          </div>
        </div>
      </section>

      <!-- 发布设置 -->
      <section class="publish-section">
        <div class="card">
          <h2 class="section-title">🚀 发布设置</h2>
          <div class="platform-grid">
            <label
              v-for="platform in platforms"
              :key="platform"
              class="platform-item"
            >
              <input
                type="checkbox"
                v-model="selectedPlatforms"
                :value="platform"
              >
              {{ platform }}
            </label>
          </div>
          <button
            class="publish-btn"
            :disabled="!hasSelectedText"
            @click="handleSend()"
          >
            发布 ({{ selectedCount }})
          </button>
        </div>
      </section>
    </div>

    <!-- 生成预览 -->
    <section class="preview-section">
      <div class="card">
        <div class="preview-header">
          <h2 class="section-title">🔍 生成预览</h2>
          <label class="select-all">
            <input
              type="checkbox"
              v-model="selectAll"
            >
            全选
          </label>
        </div>

        <!-- 局部加载状态 -->
        <div 
          v-if="isGenerating"
          class="local-loading"
        >
          <div class="loader"></div>
          <p>正在生成内容...</p>
        </div>

        <div 
          v-else
          class="text-list"
        >
          <div
            v-for="(item, index) in generatedItems"
            :key="item.id"
            class="text-item"
            :class="{ selected: item.selected }"
          >
            <div class="item-main">
              <label class="item-select">
                <input
                  type="checkbox"
                  v-model="item.selected"
                >
              </label>
              <div class="item-content">
                {{ item.content }}
              </div>
              <div class="item-actions">
                <button
                  class="icon-btn edit-btn"
                  @click="openEditor(index)"
                >
                  ✏️
                </button>
                <button
                  class="icon-btn delete-btn"
                  @click="deleteItem(item.id)"
                >
                  🗑️
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>

    <!-- 内联编辑模态框 -->
    <div 
      v-if="editingIndex !== null"
      class="edit-modal-overlay"
    >
      <div class="edit-modal">
        <h3>编辑文本</h3>
        <textarea v-model="editingContent"></textarea>
        <div class="modal-actions">
          <button @click="saveEdit">保存</button>
          <button @click="cancelEdit">取消</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed,onMounted,watch } from 'vue'
// import { v4 as uuidv4 } from 'uuid'

// import{ generateComments} from "../api/generate.js"
// import{ generateCommentsWithNoDb} from "../api/generate.js"
import{ generateCommentsToDb } from "../api/generate.js"
// import { random } from 'core-js/core/number'
import { getAllEvents, } from "../api/analysis"

import {sendMessages} from "../api/send.js"


// 页面挂载完成后调用获取事件列表方法
onMounted(() => {
  getEvents()
})
// 存储所有事件数据的响应式数组
const Events = ref([])
// 存储所有事件标题的响应式数组，用于下拉选择展示
const eventTitle = ref([])
// 当前选中的事件对象，包含该事件下的热门话题（hotwords）
const event = ref({
  hotwords :[],
})
/**
 * 获取所有事件的方法
 * 调用 API 接口 getAllEvents 获取数据
 * 将返回的数据存入 Events，并提取所有事件标题存入 eventTitle
 */
async function getEvents() {
  const res = await getAllEvents()
  Events.value = res.data;
  for (let i = 0; i < Events.value.length; i++) {
    eventTitle.value.push(Events.value[i].title)
  }
}

/**
 * 选择事件的方法
 * 根据点击的索引从 Events 中取出对应的事件对象赋值给 event
 */
function selectEvent(index) {
  event.value.hotwords= Events.value[index].hotwords
}

/**
 * 选择话题的方法
 * 根据点击的话题索引，将对应的话题词设置到 form.prompt 中
 */
function selectTopic(index){
  form.prompt=event.value.hotwords[index]
}

// 表单数据
const form = reactive({
  model: 'textInput', 
  event_id: "",
  prompt: "",
  model_type: "",
  ratio: 5,
  count: 3
})


// 监听输入模式切换，重置 prompt
watch(
  () => form.model,
  (newModel) => {
    console.log('newModel:', newModel)
    form.prompt = ''  // 切换模式时清空 prompt
    event.value.hotwords = []
  }
)

// 生成状态
const isGenerating = ref(false)

// 生成结果
const generatedItems = ref([])

// 平台相关
const platforms = ['微博', '抖音', '小红书', 'B站', '知乎']
const selectedPlatforms = ref([])

// 编辑相关
const editingIndex = ref(null)
const editingContent = ref('')

// 计算属性
const selectedCount = computed(() => 
  generatedItems.value.filter(item => item.selected).length
)

const hasSelectedText = computed(() => 
  selectedCount.value > 0 && selectedPlatforms.value.length > 0
)

const selectAll = computed({
  get: () => generatedItems.value.every(item => item.selected),
  set: (value) => {
    generatedItems.value.forEach(item => item.selected = value)
  }
})

// 生成方法
// const handleGenerate = async () => {
//   isGenerating.value = true
//   try {

//     const params = {
//       prompt: form.prompt,
//       number : form.count,
//     };
//     console.log(params)

//     let newItems;
//     // const res= await generateComments(params)
//     const res= await generateCommentsWithNoDb(params)

//     console.log(res);

//     if(res.code == 1) {
//     newItems = res.data.generated_comments.map((comment, index) => ({
//     ...comment,
//     id: index + 1 // Using index + 1 as temporary ID
//   }));

//     // if(res.code == 1){
//     //   newItems = res.data.generated_comments.map(comment => ({
//     //     ...comment,
//     //     id: crypto.randomUUID() // TODO 当前使用随机添加唯一ID，后续需要替换成数据库中的id
//     //   }));
//     }else{
//       console.log("获取生成评论失败！",res);
//     }

//     generatedItems.value = [...newItems, ...generatedItems.value]
//   } finally {
//     isGenerating.value = false
//   }
// }
const handleGenerate = async () => {
  isGenerating.value = true
  try {
    const params = {
      prompt: form.prompt,
      number: form.count,
      event_id: form.event_id,
      model_type: form.model_type,
      last_editor: ""
    };
    console.log(params)

    let newItems;
    // const res= await generateComments(params)
    const res= await generateCommentsToDb(params)

    console.log(res);

    if(res.code == 1) {
      newItems = res.data.generated_comments;
    }else{
      console.log("获取生成评论失败！",res);
    }

    generatedItems.value = [...newItems, ...generatedItems.value]
  } finally {
    isGenerating.value = false
  }
}



//发送
const handleSend = async ()=>{

  const message_list = generatedItems.value
    .filter(item => item.selected)
    .map(item => item.content);

  const params = {
    messages:message_list
  }
  console.log("发送的信息是",params)

  const res = await sendMessages(params);

  console.log(res.data)
}

// 删除项目
const deleteItem = (id) => {
  console.log(id)
  generatedItems.value = generatedItems.value.filter(item => item.id !== id)
}

// 编辑处理
const openEditor = (index) => {
  editingIndex.value = index
  editingContent.value = generatedItems.value[index].content
}

const saveEdit = () => {
  if (editingIndex.value !== null) {
    generatedItems.value[editingIndex.value].content = editingContent.value
    editingIndex.value = null
  }
}

const cancelEdit = () => {
  editingIndex.value = null
}
</script>

<style scoped>

.generate-container {
  /* max-height: 60vh; */
  overflow-y: auto;
  overflow-x: hidden;
  scrollbar-width: thin;
  scrollbar-color: #8ecae6 transparent;
  background-image: url('../background/DBack.jpg');
  background-size: cover;
  background-repeat: no-repeat;
}


/* 颜色变量 */
:root {
  --bg-main: #0d1b2a;
  --bg-surface: #1b263b;
  --text-main: #000000;
  --text-muted: #778da9;
}

.generate-container {
  padding: 2rem;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 2rem;
  box-sizing: border-box; /* 包含 padding 在高度计算中 */
  overflow-y: auto; /* 允许内容滚动 */
}

.top-section {
  display: grid;
  grid-template-columns: 1.5fr 1fr;
  gap: 2rem;
}

.card {
  background: var(--bg-surface);
  background-color: white;
  border-radius: 12px;
  padding: 1.5rem;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.2);

  height: 100%;
}

.section-title {
  color: #000;
  font-size: 1.25rem;
  margin-bottom: 1.5rem;
}

.prompt-input {
  width: 85%;
  height: 120px;
  padding: 1rem;
  background: rgb(142, 202, 230);
  border: 3px solid #8ecae6;
  border-radius: 8px;
  color: black;
  resize: vertical;
}

.config-row {
  color: #000;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1.5rem;
  margin: 1.5rem 0;
}

/* 按钮样式 */
.generate-btn,
.publish-btn {
  width: 100%;
  padding: 12px 24px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  background: linear-gradient(90deg, #007cf0 0%, #00dfd8 100%);
  color: white;
  transition: opacity 0.2s;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 加载状态 */
.local-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 1rem;
  padding: 2rem;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  margin: 1rem 0;
}

.platform-grid{
  color: #000;
}

.loader {
  width: 40px;
  height: 40px;
  border: 4px solid #8ecae6;
  border-top-color: transparent;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 文本项样式 */
.text-item {
  color: #000;
  background-color: rgb(142, 202, 230);
  border: 1px solid transparent;
  border-radius: 10px;
  padding: 1rem;
  margin: 0.75rem 0;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
  transition: all 0.3s ease;
}

.preview-header{
  color: #000;
}

.item-actions {
  display: flex;
  gap: 0.8rem;
  opacity: 0;
  transition: opacity 0.2s;
  margin-left:auto;
}

.text-item:hover {
  background-color: #2b262664;
  border: 1px solid #8ecae6;
  transform: translateY(-2px);
}

.text-item:hover .item-actions {
  opacity: 1;
}

/* 编辑模态框 */
.edit-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
}

.edit-modal {
  background: var(--bg-surface);
  padding: 2rem;
  border-radius: 8px;
  width: 500px;
}

.edit-modal textarea {
  width: 100%;
  height: 150px;
  padding: 1rem;
  margin: 1rem 0;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid #8ecae6;
  color: var(--text-main);
  border-radius: 6px;
}

.modal-actions {
  display: flex;
  gap: 1rem;
  justify-content: flex-end;
  
}



@media (max-width: 768px) {
  .top-section {
    grid-template-columns: 1fr;
  }
  
  .config-row {
    grid-template-columns: 1fr;
  }
  
  .edit-modal {
    width: 90%;
  }
}

.item-main{
  display:flex;
}

.model-change{
  text-align: left;
  color: black;
  margin-bottom: 20px;
}

.BoxInfo{
  display: flex;
  width: 100%;  
  height: 35px;
  margin-bottom: 15px;
}

.info-box {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgb(142, 202, 230);
  color: #000000;
  height: 100%;
  border: 3px solid #8ecae6;
  border-radius: 10px;
}

.eventInfo { width: 30%; }
.topicInfo { width: 40%; }
.topicSelectedInfo { width: 30%; }

.topicBox{
  display: flex;
  height: 250px;
}

.eventList {
  height: 100%;
  width: 30%;
  border-right: 3px solid #f0f0f0;
  overflow-y: auto;
  box-shadow: 0 2px 4px rgba(24, 21, 21, 0.05);
  font-family: "Segoe UI", sans-serif;
  scrollbar-width: none;
}
.topicList{
  height: 100%;
  width: 40%;
  border-right: 3px solid #ffffff;
  overflow-y: auto;
  box-shadow: 0 2px 4px rgba(24, 21, 21, 0.05);
  font-family: "Segoe UI", sans-serif;
  scrollbar-width: none;
}

.topicSelected{
  height: 100%;
  width: 30%;
}

.event-list {
  list-style: none;
  color: #000000;
  padding: 0;
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  text-align: left;
}

.event-list li {
  padding: 12px 0;
  padding-left: 20px;
  background-color: rgb(142, 202, 230);
  /* 添加左内边距以增加间隔 */
  border-bottom: 3px solid #ffffff;
  transition: background-color 0.3s ease;
  /* 添加过渡效果 */
  border-radius: 10px;
}

.event-list li:hover {
  background-color: #2b262664;
  transform: translateY(-2px);
  /* 鼠标悬停时改变背景色 */
}

.topic-list {
  list-style: none;
  color: #000000;
  padding: 0;
  margin: 0;
  font-size: 14px;
  line-height: 1.5;
  text-align: left;
}


.topic-list li {
  padding: 12px 0;
  padding-left: 20px;
  background-color: rgb(142, 202, 230);
  /* 添加左内边距以增加间隔 */
  border-bottom: 3px solid #ffffff;
  transition: background-color 0.3s ease;
  /* 添加过渡效果 */
  border-radius: 10px;
}

.empty-topic{
  color: #000;
  height: 250px;
  background-color: rgb(142, 202, 230);
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 18px;
}

.topic-list li:hover {
  background-color: #2b262664;
  transform: translateY(-2px);
  /* 鼠标悬停时改变背景色 */
}

.topicTitle{
  width: 100%;
  height: 20%;
  border-bottom: 3px solid #ffffff;
  color: #000000;
  background-color: rgb(142, 202, 230);
  display: flex;      
  align-items: center; 
  justify-content: center;
  border-radius: 10px;
}
.topicContent{
  width: 100%;
  height: 80%;
  color: #000000;
  background-color: rgb(142, 202, 230);
  display: flex;      
  align-items: center; 
  justify-content: center;
  border-radius: 10px;
}

.preview-section{
  margin-top: 40px;
}
</style>